package com.iiot.stream.tools;


import com.htiiot.common.util.JedisMultiPool;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

/**
 * 本类实现将redis中每台设备各种状态下每个月的时长进行汇总
 * 定时任务中每月3号调用执行一次
 * Created by dzm on 2018/6/7.
 */
public class RedisMonthGatherByDid implements Job{
    Logger logger  = Logger.getLogger(RedisMonthGatherByDid.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException{
        logger.info("-------------------开始汇总月份数据------------------------");
        // 获取 redis 连接
        Jedis redisHandle = JedisMultiPool.getJedis();
        Pipeline pl = redisHandle.pipelined();
        long currentTime = System.currentTimeMillis();
        // 获取上一个月的月份
        String lastMonth = LastMonth.getLastMonth();
        // 获取所有did
        String[] allDid = redisHandle.hkeys("deviceStatus").toArray(new String[]{});
        // 需要汇总的状态
        String[] statusArr = new String[]{"run","standby","fault","off"};
        for(int i = 0;i < statusArr.length;i++){
            String status = statusArr[i];
            // 当前状态，上个月的所有天
            String[] days = redisHandle.keys("deviceStatus:" + status + ":" + lastMonth + "-*").toArray(new String[]{});
            // 遍历每一个did，进行汇总
            for(int k = 0;k < allDid.length;k++){
                String tiddid = allDid[k];
                long sumLength = 0L;
                for(int j = 0;j < days.length;j++){
                    String day = days[j];
                    String dayLength = redisHandle.hget(day,tiddid);
                    // 防止redis中的数据被误操作
                    try{
                        if(!(null == dayLength)){
                            sumLength = sumLength + Long.parseLong(dayLength);
                        }
                    }catch (Exception e){
                        logger.info(e.getMessage());
                    }
                }
                // 将汇总结果写回redis
                pl.hset("deviceStatus:" + status + ":" + lastMonth,tiddid,String.valueOf(sumLength));
            }
        }
        logger.info("月份数据汇总完成，用时：" + (System.currentTimeMillis() - currentTime)/1000 + "s");
        pl.sync();
        redisHandle.close();
    }
}
